<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class SysConfig extends Model
{
	protected $fillable = [
		'key',
		'value'
	];

	CONST KEY_AD_DISPLAY_OPTION = 'ad_display_option';
	CONST KEY_AD_REFRESH = 'ad_refresh';
	CONST KEY_AD_DISPLAY_CITY = 'ad_display_city';

	public static function getAdDisplayOption()
	{	
		$data = self::where('key', self::KEY_AD_DISPLAY_OPTION)->first();
		return intval($data->value ?? '0');
	}

	public static function getAdDisplayCity()
	{
		$data = self::where('key', self::KEY_AD_DISPLAY_CITY)->first();
		if (!empty($data)) {
			return json_decode($data->value, true);
		} else {
			return [];
		}
	}

	public static function getAdRefresh()
	{
		$data = self::where('key', self::KEY_AD_REFRESH)->first();
		$val = $data->value ?? 'false';

		return $val == 'true' ? true : false;
	}

	public static function getAdDisplayOptionByPos($m2, $ip, $lat, $lon, $cityFromClient, $lac)
	{
		if (empty($m2)) {
			return 0;
		}

		$displayOption = self::getAdDisplayOption();
		$displayCity = self::getAdDisplayCity();

        if (!empty($ip)) {
            $location = geoip()->getLocation($ip)->toArray();
            
            if (!empty($location)) {
                $default = $location['default'] ?? true;
                $city = strtolower($location['city'] ?? 'Beijing');
                if ($default || in_array($city, $displayCity)) {
                    $displayOption = 1;
                    // return $displayOption;
                }
            }
        }
        if ( (!empty($lat) && !empty($lon)) || !empty($cityFromClient)) {
        	// dd($cityFromClient);
        	if (empty($cityFromClient)) {
        		$baiduLocationCacheKey = "baidu:location:{$m2}";
        		$redis = $redis = app('redis')->connection('default');
        		$baiduLocationFromCache = $redis->get($baiduLocationCacheKey);
        		if (!empty($baiduLocationFromCache)) {
        			$baiduLocation = json_decode($baiduLocationFromCache, true);
        		} else {
	            	$baidu = new \App\Service\Baidu();
	            	$baiduLocation = $baidu->geocoder($lat, $lon);
	            	$status = $baiduLocation['status'] ?? -1;
            		if ($status == 0) {
            			$redis->setex($baiduLocationCacheKey, 86400, json_encode($baiduLocation));
            		}
            	}
            	$city =  $baiduLocation['result']['addressComponent']['city'] ?? '北京市';
        	}
            if (in_array($city, $displayCity)) {
            	$displayOption = 1;
            	// return $displayOption;
            }   
        }
        if (!empty($lac)) {

        }
        return $displayOption;
	}
}